﻿using Microsoft.Web.WebView2.WinForms;
using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace WebView2Project
{
    public partial class Form1 : Form
    {
        private const string HOME_URL = "https://www.bing.com";
        private const string DEFAULT_TITLE = "WebView2 浏览器";

        public Form1()
        {
            InitializeComponent();
        }

        private async void Form1_Load(object sender, EventArgs e)
        {
            await InitializeWebViewAsync();
        }

        /// <summary>
        /// 初始化WebView2控件
        /// </summary>
        private async Task InitializeWebViewAsync()
        {
            try
            {
                // 设置用户数据文件夹
                var userDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "WebView2Browser");
                
                // 创建WebView2环境
                var environment = await CoreWebView2Environment.CreateAsync(null, userDataFolder);
                
                // 初始化WebView2核心
                await webView21.EnsureCoreWebView2Async(environment);

                // 设置事件处理程序
                SetupWebViewEvents();

                // 导航到主页
                await NavigateToUrlAsync(HOME_URL);
                
                UpdateStatus("WebView2 初始化完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化 WebView2 失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus("初始化失败");
            }
        }

        /// <summary>
        /// 设置WebView2事件处理程序
        /// </summary>
        private void SetupWebViewEvents()
        {
            // 导航开始事件
            webView21.CoreWebView2.NavigationStarting += (sender, args) =>
            {
                UpdateStatus($"正在加载: {args.Uri}");
                txtAddress.Text = args.Uri;
                UpdateNavigationButtons();
            };

            // 导航完成事件
            webView21.CoreWebView2.NavigationCompleted += (sender, args) =>
            {
                if (args.IsSuccess)
                {
                    UpdateStatus("加载完成");
                    this.Text = $"{webView21.CoreWebView2.DocumentTitle} - {DEFAULT_TITLE}";
                }
                else
                {
                    UpdateStatus("加载失败");
                    MessageBox.Show($"导航失败: {args.WebErrorStatus}", "导航错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                
                txtAddress.Text = webView21.CoreWebView2.Source;
                UpdateNavigationButtons();
            };

            // 文档标题改变事件
            webView21.CoreWebView2.DocumentTitleChanged += (sender, args) =>
            {
                this.Text = $"{webView21.CoreWebView2.DocumentTitle} - {DEFAULT_TITLE}";
            };

            // 源改变事件
            webView21.CoreWebView2.SourceChanged += (sender, args) =>
            {
                txtAddress.Text = webView21.CoreWebView2.Source;
            };

            // 历史改变事件
            webView21.CoreWebView2.HistoryChanged += (sender, args) =>
            {
                UpdateNavigationButtons();
            };

            // 权限请求事件
            webView21.CoreWebView2.PermissionRequested += (sender, args) =>
            {
                var result = MessageBox.Show(
                    $"网站 {args.Uri} 请求 {args.PermissionKind} 权限。是否允许？",
                    "权限请求",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);

                args.State = result == DialogResult.Yes ? 
                    CoreWebView2PermissionState.Allow : 
                    CoreWebView2PermissionState.Deny;
            };

            // 新窗口请求事件
            webView21.CoreWebView2.NewWindowRequested += (sender, args) =>
            {
                args.Handled = true;
                // 在当前窗口中打开新链接
                webView21.CoreWebView2.Navigate(args.Uri);
            };

            // 添加主机对象到脚本
            AddHostObjectToScript();
        }

        /// <summary>
        /// 添加C#对象到JavaScript环境
        /// </summary>
        private void AddHostObjectToScript()
        {
            try
            {
                var hostObject = new BrowserHostObject();
                webView21.CoreWebView2.AddHostObjectToScript("browserHost", hostObject);
                UpdateStatus("JavaScript互操作已启用");
            }
            catch (Exception ex)
            {
                UpdateStatus($"JavaScript互操作设置失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 导航到指定URL
        /// </summary>
        private async Task NavigateToUrlAsync(string url)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(url))
                    return;

                // 简单的URL格式化
                if (!url.StartsWith("http://") && !url.StartsWith("https://") && !url.StartsWith("file://"))
                {
                    // 如果看起来像搜索查询，使用搜索引擎
                    if (!url.Contains(".") || url.Contains(" "))
                    {
                        url = $"https://www.bing.com/search?q={Uri.EscapeDataString(url)}";
                    }
                    else
                    {
                        url = "https://" + url;
                    }
                }

                webView21.CoreWebView2.Navigate(url);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导航失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 更新导航按钮状态
        /// </summary>
        private void UpdateNavigationButtons()
        {
            if (webView21?.CoreWebView2 != null)
            {
                btnBack.Enabled = webView21.CoreWebView2.CanGoBack;
                btnForward.Enabled = webView21.CoreWebView2.CanGoForward;
            }
        }

        /// <summary>
        /// 更新状态栏
        /// </summary>
        private void UpdateStatus(string message)
        {
            lblStatus.Text = message;
            lblProgress.Text = DateTime.Now.ToString("HH:mm:ss");
        }

        #region 按钮事件处理程序

        private void btnBack_Click(object sender, EventArgs e)
        {
            try
            {
                if (webView21?.CoreWebView2?.CanGoBack == true)
                {
                    webView21.CoreWebView2.GoBack();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"后退失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnForward_Click(object sender, EventArgs e)
        {
            try
            {
                if (webView21?.CoreWebView2?.CanGoForward == true)
                {
                    webView21.CoreWebView2.GoForward();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"前进失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                webView21?.CoreWebView2?.Reload();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"刷新失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void btnHome_Click(object sender, EventArgs e)
        {
            await NavigateToUrlAsync(HOME_URL);
        }

        private async void btnGo_Click(object sender, EventArgs e)
        {
            await NavigateToUrlAsync(txtAddress.Text.Trim());
        }

        private void txtAddress_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.Handled = true;
                btnGo.PerformClick();
            }
        }

        private void btnDevTools_Click(object sender, EventArgs e)
        {
            try
            {
                webView21?.CoreWebView2?.OpenDevToolsWindow();
                UpdateStatus("开发者工具已打开");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开开发者工具失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (webView21?.CoreWebView2 != null)
                {
                    await webView21.CoreWebView2.PrintAsync(null);
                    UpdateStatus("打印对话框已打开");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打印失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void btnJavaScript_Click(object sender, EventArgs e)
        {
            try
            {
                var jsForm = new JavaScriptForm();
                if (jsForm.ShowDialog() == DialogResult.OK)
                {
                    var script = jsForm.JavaScriptCode;
                    if (!string.IsNullOrWhiteSpace(script))
                    {
                        var result = await webView21.CoreWebView2.ExecuteScriptAsync(script);
                        
                        var resultForm = new ScriptResultForm();
                        resultForm.SetResult(script, result);
                        resultForm.ShowDialog();
                        
                        UpdateStatus("JavaScript执行完成");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"执行JavaScript失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                webView21?.Dispose();
            }
            catch (Exception ex)
            {
                // 忽略关闭时的异常
                System.Diagnostics.Debug.WriteLine($"关闭时异常: {ex.Message}");
            }
        }
    }

    /// <summary>
    /// 提供给JavaScript的主机对象
    /// </summary>
    [System.Runtime.InteropServices.ComVisible(true)]
    public class BrowserHostObject
    {
        public string GetCurrentTime()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public void ShowMessage(string message)
        {
            MessageBox.Show(message, "来自网页的消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public string GetSystemInfo()
        {
            return $"操作系统: {Environment.OSVersion}\n" +
                   $"机器名: {Environment.MachineName}\n" +
                   $"用户名: {Environment.UserName}\n" +
                   $".NET版本: {Environment.Version}";
        }
    }
}
